package com.ruoyi.factory.taxShare.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.apilog.domain.ApiLog;
import com.ruoyi.factory.apilog.mapper.ApiLogMapper;
import com.ruoyi.factory.common.utils.IdGen;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import com.ruoyi.factory.taxShare.common.CharUtil;
import com.ruoyi.factory.taxShare.domain.TaxCustomerInfo;
import com.ruoyi.factory.taxShare.domain.TaxNotify;
import com.ruoyi.factory.taxShare.domain.Taxjs;
import com.ruoyi.factory.taxShare.domain.Taxxs;
import com.ruoyi.factory.taxShare.mapper.TaxCustomerInfoMapper;
import com.ruoyi.factory.taxShare.mapper.TaxNotifyMapper;
import com.ruoyi.factory.taxShare.mapper.TaxjsMapper;
import com.ruoyi.factory.taxShare.mapper.TaxxsMapper;
import com.ruoyi.factory.taxShare.service.TaxHandService;
import com.ruoyi.factory.common.task.AsyncFactoryLog;
import com.ruoyi.framework.manager.AsyncManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TaxHandServiceImpl implements TaxHandService {

    protected final Logger logger = LoggerFactory.getLogger(TaxHandServiceImpl.class);

    @Value("${tax.sendUrl}")
    private String sendUrl;
    @Value("${tax.xsfplx}")
    private String xsfplx;
    @Value("${tax.jsqdlx}")
    private String jsqdlx;
    @Value("${tax.xsfpgsmc}")
    private String xsfpgsmc;
    @Value("${tax.jsqdgsmc}")
    private String jsqdgsmc;
    @Value("${tax.sptsgsmc}")
    private String sptsgsmc;
    @Autowired
    private TaxNotifyMapper taxNotifyMapper;
    @Autowired
    private TaxxsMapper taxxsMapper;
    @Autowired
    private TaxjsMapper taxjsMapper;
    @Autowired
    private ApiLogMapper apiLogMapper;
    @Autowired
    private TaxCustomerInfoMapper taxCustomerInfoMapper;

    public AjaxResult test(JSONObject reqMap, HttpServletRequest request){
        JSONArray jsonArray = reqMap.optJSONArray("pks");
        String s = jsonArray.toString();
        String[] strings = new String[jsonArray.size()];
        String[] String2 = (String[])jsonArray.toArray(strings);
//        List<Taxxs> taxxs = taxxsMapper.selectTaxxsListByids(String2);
        return new AjaxResult(200,"success");
    }

    public AjaxResult taxUpDataBill(JSONObject reqMap, HttpServletRequest request){
        logger.info("税务平台请求回调参数: "+reqMap);
        //判断是否需要记录日志
        if (true) {
            // 添加日志
            ApiLog apiLog = new ApiLog();
            String desc = "税务平台回调";
            apiLog.setRequestId("税务平台");
            apiLog.setApiName(desc);
            apiLog.setInputParam(JSONObject.fromObject(reqMap).toString());
            AsyncManager.me().execute(AsyncFactoryLog.recordApiLog(apiLog));
        }
        //应该设置可以批量接收数据
        String remoteAddr = request.getRemoteAddr();
        String localAddr = request.getLocalAddr();
        if(StringUtils.isEmpty(localAddr)){
            logger.info("金税平台回调更新单据状态请联系管理员开放访问白名单");
            return new AjaxResult(500,"请联系管理员开放访问白名单");
        }
        //单据类型billtype 10-销售发票 20-交易结算清单
        String billtype = reqMap.optString("sjlx");
        //单据id
        String billid = reqMap.optString("djbh");
        //金税发票号
        String taxcode = reqMap.optString("fphm");
        //金税发票号
        String qdfphm = reqMap.optString("qdfphm");
        //当金税发票号为空则取金税发票号
        if(StringUtils.isEmpty(taxcode)){
            if(StringUtils.isNotEmpty(qdfphm)){
                taxcode = qdfphm;
            }
        }
        if (StringUtils.isEmpty(taxcode)) {
            return new AjaxResult(500, "fphm不可为空");
        }
        //发票日期格式日期格式 yyyy-MM-dd
        String taxdate = reqMap.optString("kprq");
        //校验单据数据是否为空
        if (StringUtils.isEmpty(billtype)) {
            return new AjaxResult(500, "sjlx不可为空");
        }
        if (StringUtils.isEmpty(billid)) {
            return new AjaxResult(500, "djbh不可为空");
        }
        if (StringUtils.isEmpty(taxdate)) {
            return new AjaxResult(500, "kprq不可为空");
        }
        //判断是否有发票号,有则返回,无则回调

        //防止多次调用
//        apiLogMapper.insertnotify(taxcode);
        //判断单据类型  czlx 红冲的不处理  作废的 删除 2- 作废 3-红冲
        String czlx = reqMap.optString("czlx");
        if(StringUtils.isNotEmpty(czlx) && "3".equals(czlx)){
            //红冲发票不做处理直接返回
            return new AjaxResult(0,"SUCCESS");
        }
        //根据 类型和编码和类型回写金税发票号和日期
        if(xsfplx.contains(billtype)){ //之后做为自动配置
            //01-销售发票 根据单据id修改  销售发票 付款单 表头金税单据号和金税日期 先查询再修改  单据号可能有多个以逗号分隔
            TaxNotify pt = new TaxNotify();
            pt.setXsid(billid);
            //根据id查询
            List<TaxNotify> taxNotifies = taxNotifyMapper.selectTaxNotifyListxs(pt);
            //不为空并且只有一个
            if(!taxNotifies.isEmpty() && taxNotifies.size()==1){
                TaxNotify taxNotify = taxNotifies.get(0);
                String xsjscode = taxNotify.getXsjscode();
                String xsjsdate = taxNotify.getXsjsdate();
                //判断金税不为空
                if(StringUtils.isNotEmpty(xsjscode) && !xsjscode.equals("~")){
                    String xsjscode1 = taxNotify.getXsjscode();
                    //如果不包含该发票号则进行保存
                    if(!xsjscode1.contains(taxcode)){
                        //如果销售发票金税编码不为空 则整理 并给销售和应收发票号赋值
                        if("2".equals(czlx)){
                            //删除作废发票号和日期
                            String newStr = CharUtil.rep(xsjscode, taxcode);
                            String newStr2 = CharUtil.rep(xsjsdate, taxdate);
                            xsjscode = newStr;
                            xsjsdate = newStr2;
                        }else{
                            xsjscode = xsjscode+","+taxcode;
                            xsjsdate = xsjsdate+","+taxdate;
                        }
                        taxNotify.setXsjscode(xsjscode);
                        taxNotify.setXsjsdate(xsjsdate);
                        taxNotify.setYsjscode(xsjscode);
                        taxNotify.setYsjsdate(xsjsdate);
                    }
                }else{
                    //如果为空则直接复制金税号和日期
                    taxNotify.setXsjscode(taxcode);
                    taxNotify.setXsjsdate(taxdate);
                    taxNotify.setYsjscode(taxcode);
                    taxNotify.setYsjsdate(taxdate);
                }
                taxNotifyMapper.updateTaxNotifyxs(taxNotify);
                taxNotifyMapper.updateTaxNotifyxsys(taxNotify);
            }
        }else if(jsqdlx.contains(billtype)){
            //02-结算清单 收款单 付款单的 单据号和日期 先查询再修改   单据号可能有多个以逗号分隔
            TaxNotify pt = new TaxNotify();
            pt.setJsid(billid);
            //根据id查询
            List<TaxNotify> taxNotifies = taxNotifyMapper.selectTaxNotifyListjs(pt);
            //不为空并且只有一个
            if(!taxNotifies.isEmpty() && taxNotifies.size()==1){
                TaxNotify taxNotify = taxNotifies.get(0);
                String jsjscode = taxNotify.getJsjscode();
                //判断金税不为空
                if(StringUtils.isNotEmpty(jsjscode) && !jsjscode.equals("~")){
                    if(!jsjscode.contains(taxcode)){
                        //如果销售发票金税编码不为空 则整理 并给销售和应收发票号赋值
                        jsjscode = jsjscode+","+taxcode;
                        taxdate = taxdate+","+taxdate;
                    }
                    taxNotify.setJsjscode(jsjscode);
                    taxNotify.setJsjsdate(taxdate);
                    taxNotify.setYsjscode(jsjscode);
                    taxNotify.setYsjsdate(taxdate);
                    taxNotify.setYfjscode(jsjscode);
                    taxNotify.setYfjsdate(taxdate);
                }else{
                    //如果为空则直接复制金税号和日期
                    taxNotify.setJsjscode(taxcode);
                    taxNotify.setJsjsdate(taxdate);
                    taxNotify.setYsjscode(taxcode);
                    taxNotify.setYsjsdate(taxdate);
                    taxNotify.setYfjscode(taxcode);
                    taxNotify.setYfjsdate(taxdate);
                }
                taxNotifyMapper.updateTaxNotifyjs(taxNotify);
                taxNotifyMapper.updateTaxNotifyjsys(taxNotify);
                taxNotifyMapper.updateTaxNotifyjsyf(taxNotify);
            }
        }else{
            return new AjaxResult(500,"error","不存在的单据类型");
        }
        return new AjaxResult(0,"SUCCESS");
    }

    @Override
    public AjaxResult invoicePushParamjsqd(String pjson) {
        String uuid = IdGen.uuid();
        String desc = uuid+"erp内部清单结算请求税务平台单据推送";
        logger.info(desc+"请求参数: "+pjson);
        //处理入参数据
        JSONObject jsonObject = JSONObject.fromObject(pjson);

        String[] string2 = null;
        String billid = jsonObject.optString("billid");
        //审批中心来源标识
        if(StringUtils.isNotEmpty(billid) && !"~".contains(billid)){
            String[] string3={billid};
            string2 = string3;
        }else{
            JSONArray jsonArray1 = jsonObject.optJSONArray("pks");
            String[] strings = new String[jsonArray1.size()];
            string2 = (String[])jsonArray1.toArray(strings);
        }

        //1.获取erp中两种单据的数据
        List<String> list = new ArrayList<>();
//        String bcsbyy="";
        for (String ss1 : string2) {
            List<Taxjs> taxjs = taxjsMapper.selectTaxjsListByids(ss1);
            Taxjs taxjs1 = taxjs.get(0);
            if(jsqdgsmc.contains(taxjs1.getZzmc())) return new AjaxResult(200, "success",string2);
            //2.处理erp中传的数据
            String params = billPushTaxParamjsqd(taxjs);

            if (StringUtils.isNotEmpty(params)) {
                //3.向税务共享平台推送数据
                String url = sendUrl + "/dkpdj/ext/djtsV3";
                logger.info(desc+"V3接口 地址: " + url);
                logger.info(desc+"V3接口 入参: " + params);
                String s = OkHttpUtils.okHttpPost(url, params);
                logger.info(desc+"V3接口 返参: " + s);
                JSONObject jsonObject1 = JSONObject.fromObject(s);
                JSONArray jsonArray = jsonObject1.optJSONArray("data");
                JSONObject o = (JSONObject)jsonArray.get(0);
                String bczt = o.optString("bczt");
                if("0".equals(bczt)){
                    int i = taxjsMapper.updateTaxjsStatus(ss1);
                    logger.info(desc+"更新erp已推送状态 " + i);
                    list.add(ss1);
                }else{
                    logger.info(desc+"失败: " + o.optString("bcsbyy"));
                }
//                bcsbyy = bcsbyy + o.optString("bcsbyy");
                //判断是否需要记录日志
                if (true) {
                    // 添加日志
                    JSONObject jsonObj = JSONObject.fromObject(s);
                    ApiLog apiLog = new ApiLog();
                    String desc2 = desc+"V3接口";
                    if ("0".equals(bczt)) {
                        desc2 = desc2 + "成功";
                    } else {
                        desc2 = desc2 + "失败";
                    }
                    apiLog.setRequestId("税务平台");
                    apiLog.setApiName(desc2);
                    apiLog.setApiUrl(url);
                    apiLog.setInputParam(JSONObject.fromObject(params).toString());
                    apiLog.setOutParam(jsonObj.toString());
//                    apiLog.setPayInputParam(param);
//                    apiLog.setPayOutParam(result);
                    AsyncManager.me().execute(AsyncFactoryLog.recordApiLog(apiLog));
                }
            }
        }
      if(!list.isEmpty()){
          return new AjaxResult(200, "success", list);
      }
      return new AjaxResult(500, "fail", "失败");
    }


    /**
     * @author: Liujiaji
     * @date: 2023/8/11 11:16
     * @description: TODO 处理erp信息匹配到税务平台
     * @param: [mapslist]
     * @return: java.lang.String
     **/
    public String billPushTaxParamjsqd(List<Taxjs> mapslist) {
        Taxjs taxjs = mapslist.get(0);
        //处理参数
        JSONObject datatdhy = new JSONObject();
        datatdhy.put("tdyslxbl", "");
        datatdhy.put("tdyslx", "");
        datatdhy.put("tdysnr", "");
        JSONArray arraytdhy = new JSONArray();
        arraytdhy.add(datatdhy);

        JSONArray arraymxx = new JSONArray();
        //动态添加 明细行信息
        for (Taxjs taxjs1 : mapslist) {
            JSONObject datamxx = new JSONObject();
            datamxx.put("djhh", taxjs1.getHh());
            datamxx.put("spdm", taxjs1.getWlcode());
            if(StringUtils.isNotEmpty(taxjs1.getKhwlmc()) && !taxjs1.getKhwlmc().equals("~")){
                datamxx.put("spmc", taxjs1.getKhwlmc());
                if(StringUtils.isNotEmpty(taxjs1.getKhgg()) && !"~".equals(taxjs1.getKhgg())){
                    datamxx.put("ggxh", taxjs1.getKhgg());
                }
                datamxx.put("jldw", taxjs1.getKhdwmc());

                //根据单位转换
                String hslv = taxjs1.getHslv();
                if(StringUtils.isNotEmpty(hslv) && !hslv.equals("~")){
                    String[] split = hslv.split("/");
                    String s = split[0];
                    String s1 = split[1];
                    BigDecimal dwzh = new BigDecimal(s).divide(new BigDecimal(s1),7, BigDecimal.ROUND_HALF_UP);
                    //根据换算率换算 数量和单价 //商品数量
                    datamxx.put("spsl", new BigDecimal(taxjs1.getSli()).divide(dwzh, 6, BigDecimal.ROUND_HALF_UP).toString());
                    //含税单价
//                    datamxx.put("hsdj", new BigDecimal(taxjs1.getHsdj()).multiply(dwzh).setScale(6, BigDecimal.ROUND_HALF_UP).toString());
                    //不含税单价
//                    datamxx.put("bhsdj", new BigDecimal(taxjs1.getWsdj()).multiply(dwzh).setScale(6, BigDecimal.ROUND_HALF_UP).toString());
                }
            }else{
                datamxx.put("spmc", taxjs1.getWlmc());
                if(StringUtils.isNotEmpty(taxjs1.getGg()) && !"~".equals(taxjs1.getGg())){
                    datamxx.put("ggxh", taxjs1.getGg());
                }

                datamxx.put("jldw", taxjs1.getDwmc());
                datamxx.put("spsl", taxjs1.getSli());
                //含税单价
//                datamxx.put("hsdj", new BigDecimal(taxjs1.getHsdj()).setScale(6,BigDecimal.ROUND_HALF_UP).toString());
                //不含税单价
//                datamxx.put("bhsdj", new BigDecimal(taxjs1.getWsdj()).setScale(6,BigDecimal.ROUND_HALF_UP).toString());
            }

            datamxx.put("sppc", taxjs1.getPch());

            //含税金额
            datamxx.put("hsje", new BigDecimal(taxjs1.getDjjshj()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            //不含税金额
            datamxx.put("bhsje", new BigDecimal(taxjs1.getWsje()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            //税 额
            datamxx.put("se", new BigDecimal(taxjs1.getShuie()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            //税率改为小数
            datamxx.put("tax", new BigDecimal(taxjs1.getSlv()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toString());
            datamxx.put("spbm", "");
            //零税率标识
            datamxx.put("lslbs", "");
            //优惠政策标识
            datamxx.put("yhzcbs", "");
            arraymxx.add(datamxx);
        }

        JSONObject dataj1 = new JSONObject();
        dataj1.put("gsdm", taxjs.getZzdm());
        //内销:10；外销:20;内部交易:30
        dataj1.put("sjlx", "30");
        dataj1.put("sjly", "1");
        //开票类型 暂时0 fplx
        dataj1.put("kplx", "0");
        dataj1.put("djbh", taxjs.getSethid());
//        dataj1.put("khdm", taxjs.getJszzid());
//        dataj1.put("khmc", taxjs.getKhmc());
        dataj1.put("khmc", taxjs.getJszz());
        //发票类型代码(004-专票 007-普票 025-卷票 026-电子票01-全电专 02-全电普)
        if("32-01".equals(taxjs.getFplx())){
            dataj1.put("fplxdm", "004");
        }else if("32-Cxx-01".equals(taxjs.getFplx())){
            dataj1.put("fplxdm", "026");
        }else if("32-Cxx-02".equals(taxjs.getFplx())){
            dataj1.put("fplxdm", "01");
        }else if("32-Cxx-03".equals(taxjs.getFplx())){
            dataj1.put("fplxdm", "02");
        }

        //00-正常发票(默认) 08-成品油 02-收购发票 12-机动车专票
        dataj1.put("tspz", "00");
        dataj1.put("djrq", taxjs.getDjrq());
        //备注为空则不传
        if(StringUtils.isNotEmpty(taxjs.getBz()) && !"~".equals(taxjs.getBz())){
            dataj1.put("bz", taxjs.getBz());
        }
        //含税标志
        if (Integer.valueOf(taxjs.getSlv()) > 0) {
            dataj1.put("hsbz", "1");
        } else {
            dataj1.put("hsbz", "0");
        }
        //明细含税合计
//        dataj1.put("je", taxjs.getJshj());
        //税率改为小数
//        dataj1.put("tax", new BigDecimal(taxjs.getSlv()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toString());
        dataj1.put("djlx", "0");
        dataj1.put("kz1", taxjs.getDjh());
        //结算清单没有是否开具发票字段 固传Y
        dataj1.put("kz3", "Y");
        dataj1.put("mxxx", arraymxx);
//        dataj1.put("tdhy",arraytdhy);

        JSONArray parray = new JSONArray();
        parray.add(dataj1);
        JSONObject pram = new JSONObject();
        pram.put("data", parray);

        String params = pram.toString();
        return params;
    }

    /**
     * 获取单据数据推送到税务共享平台 1.销售发票 2.内部结算清单维护  3.新乡瑞丰点击保存状态为审批通过则进行处理
     */
    @Override
    public AjaxResult invoicePushParamxsfp(String pjson) {
        String uuid = IdGen.uuid();
        String desc = uuid+"销售发票单据推送到税务平台";
        logger.info(desc+"请求参数: "+pjson);
        //处理入参数据
        JSONObject jsonObject = JSONObject.fromObject(pjson);

        //处理根据审批通过处理数据
        String[] string2 = null;
        String billid = jsonObject.optString("billid");
        //审批中心来源标识
        Boolean spresourceflag = false;
        if(StringUtils.isNotEmpty(billid) && !"~".contains(billid)){
            String[] string3 = {billid};
            string2 = string3;
            //如果不是需要审批推送的公司则返回
            List<Taxxs> taxxs = taxxsMapper.selectTaxxsListByids(billid);
            Taxxs taxxs1 = taxxs.get(0);
            String gsmc = taxxs1.getGsmc();
            logger.info(desc+"推送金税平台taxxs1数据111: "+taxxs1.toString());
            // 只推送需要审批通过推送的公司
            if(!sptsgsmc.contains(gsmc)) return new AjaxResult(200, "success");
            spresourceflag = true;
        }else{
            JSONArray jsonArray1 = jsonObject.optJSONArray("pks");
            String[] strings = new String[jsonArray1.size()];
            string2 = (String[])jsonArray1.toArray(strings);
        }

        String params ="";
        //1.获取erp中两种单据的数据
        List<String> list = new ArrayList<>();
//        String bcsbyy="";
        for (String ss1 : string2) {
            List<Taxxs> taxxs = taxxsMapper.selectTaxxsListByids(ss1);
            //3. 判断内外销
            if(taxxs.size() == 0){
                logger.info("根据id"+ss1+"获取的taxxs为空");
                return new AjaxResult(200, "success",string2);
            }
            Taxxs taxxs1 = taxxs.get(0);
            logger.info(desc+"推送金税平台taxxs1数据222: "+taxxs1.toString());
            String gsmc = taxxs1.getGsmc();
            //公司过滤
            if(xsfpgsmc.contains(gsmc)) return new AjaxResult(200, "success",string2);
            //判断是否是需要审批通过推送单据的公司 包含的话则审批状态应为通过 或者来源标识为审批中心推送
            if(sptsgsmc.contains(gsmc)){
                //来源是否是审批中心 为true则直接放行
                if(!spresourceflag){
                    // 判断审批状态 单据状态为2则审批通过放行
                    String djzt = taxxs1.getDjzt();
                    if(!"2".equals(djzt)){
                        logger.info(desc+"推送金税平台单据状态未审批通过: "+taxxs1.toString());
                        return new AjaxResult(200, "success",string2);
                    }
                }
            }
            //金税按钮表示是否为Y Y则通过点击传金税按钮生成
            Boolean jsan1 = "Y".equals(jsonObject.optString("jsan")) ? true : false;
            if(StringUtils.isNotEmpty(taxxs1.getYwlc())&&"成品内销流程、原料销售流程、跨组织销售业务流程、跨组织销售业务流程(豪润达)".contains(taxxs1.getYwlc())){
                if("跨组织销售业务流程、跨组织销售业务流程(豪润达)".contains(taxxs1.getYwlc())){
                    if("增值税专用发票（纸票）、数电发票-电子专票（电子票）".contains(taxxs1.getFplxname())){
                        //内销 处理erp中传的数据
                        params = billPushTaxParamxsfpnx(taxxs, jsan1);
                    }else if("增值税电子普通发票（电子）、数电发票-电子普票（电子票）".contains(taxxs1.getFplxname())){
                        //外销 处理erp中传的数据
                        params = billPushTaxParamxsfpwx(taxxs, jsan1);
                    }
                }else{
                    //内销 处理erp中传的数据
                    params = billPushTaxParamxsfpnx(taxxs, jsan1);
                }
            }else if(StringUtils.isNotEmpty(taxxs1.getYwlc())&&"一般贸易销售流程、进料加工销售流程、出口合同(自提)".contains(taxxs1.getYwlc())){
                //外销 处理erp中传的数据
                params = billPushTaxParamxsfpwx(taxxs, jsan1);
            }

            if (StringUtils.isNotEmpty(params)) {
                //3.向税务共享平台推送数据
                String url = sendUrl + "/dkpdj/ext/djtsV3";
                logger.info(desc+"单据推送V3接口 地址: " + url);
                logger.info(desc+"单据推送V3接口 入参: " + params);
                String s = OkHttpUtils.okHttpPost(url, params);
                logger.info(desc+"单据推送V3接口 返参: " + s);
                JSONObject jsonObject1 = JSONObject.fromObject(s);
                JSONArray jsonArray = jsonObject1.optJSONArray("data");
                JSONObject o = (JSONObject)jsonArray.get(0);
                String bczt = o.optString("bczt");
                //回写信息
                if("0".equals(bczt)){
                    int i = taxxsMapper.updateTaxxsStatus(ss1);
                    logger.info(desc+ss1+"已完成推送状态更新" + i);
                    //成功
                    list.add(ss1);
                }else{
                    logger.info(desc+"单据推送失败: " + o.optString("bcsbyy"));
                }
//                if (!"0".equals(bczt)) bcsbyy = bcsbyy + o.optString("bcsbyy");
                //判断是否需要记录日志
                if (true) {
                    // 添加日志
                    JSONObject jsonObj = JSONObject.fromObject(s);
                    ApiLog apiLog = new ApiLog();
                    String desc2 = desc+"单据推送V3接口";
                    if ("0".equals(bczt)) {
                        desc2 = desc2 + "成功";
                    } else {
                        desc2 = desc2 + "失败";
                    }
                    apiLog.setRequestId("税务平台");
                    apiLog.setApiName(desc2);
                    apiLog.setApiUrl(url);
                    apiLog.setInputParam(JSONObject.fromObject(params).toString());
                    apiLog.setOutParam(jsonObj.toString());
//                    apiLog.setPayInputParam(param);
//                    apiLog.setPayOutParam(result);
                    AsyncManager.me().execute(AsyncFactoryLog.recordApiLog(apiLog));
                }
            }
        }

        if(!list.isEmpty()){
            return new AjaxResult(200, "success",list);
        }
//        if(StringUtils.isNotEmpty(bcsbyy)){
//            return new AjaxResult(500, "fail",bcsbyy);
//        }
        return new AjaxResult(200, "success",string2);
    }

    /**
     * 处理erp信息匹配到税务平台 内销
     */
    public String billPushTaxParamxsfpnx(List<Taxxs> mapslist, Boolean jsan) {
        Taxxs taxxs = mapslist.get(0);
        //判断内销和外销 内销和外销处理逻辑不一样
        String sfkjfp = taxxs.getSfkjfp();
        if (!"Y".equals(sfkjfp)){
            sfkjfp = "N";
        }
        //传金税按钮为真则直接放行 为假则进行是否传金税校验
        JSONObject dataj1 = new JSONObject();
        if(!jsan){
            //如果开具发票为Y则传金税 样品销售业务流则不传金税
            if(!"Y".equals(sfkjfp)|| "样品销售业务流".equals(taxxs.getYwlc()) ){
                return null;
            }
        }else{
            String pzh = taxxs.getPzh();
            String pzrq = taxxs.getPzrqn()+"-"+taxxs.getPzrqy();
            dataj1.put("kz2",pzh);
            dataj1.put("kz4",pzrq);
        }
        //处理参数
        JSONObject datatdhy = new JSONObject();
        datatdhy.put("tdyslxbl", "");
        datatdhy.put("tdyslx", "");
        datatdhy.put("tdysnr", "");
        JSONArray arraytdhy = new JSONArray();
        arraytdhy.add(datatdhy);

        //动态添加 明细行信息
        JSONArray arraymxx = new JSONArray();
        //含税标识1含税,0不含税
        String hsbz = "0";
        for (Taxxs taxxs1 : mapslist) {
            //如果大于0则是1 不大于0不处理 明细中有一个含税则是1
            if (Integer.valueOf(taxxs1.getSlv()) > 0) {
                hsbz = "1";
            }
            JSONObject datamxx = new JSONObject();
            String khwlmc = taxxs1.getKhwlmc();
            String wlmc = taxxs1.getWlmc();
            if("折扣".equals(wlmc)){
                if(StringUtils.isNotEmpty(taxxs.getKhwlmc()) && !taxxs.getKhwlmc().equals("~")){
                    datamxx.put("spmc", taxxs.getKhwlmc());
                }else{
                    datamxx.put("spmc", taxxs.getWlmc());
                }
            }else if(StringUtils.isNotEmpty(khwlmc) && !khwlmc.equals("~")){
                //客户物料不为空则使用客户物料
                datamxx.put("spmc", taxxs1.getKhwlmc());
                //处理规格型号为~字符
                if(StringUtils.isNotEmpty(taxxs1.getKhgg()) && !"~".equals(taxxs1.getKhgg())){
                    datamxx.put("ggxh", taxxs1.getKhgg());
                }
                datamxx.put("jldw", taxxs1.getKhdwmc());
                //根据单位转换
                String hslv = taxxs1.getHslv();
                if(StringUtils.isNotEmpty(hslv) && !hslv.equals("~")){
                    String[] split = hslv.split("/");
                    String s = split[0];
                    String s1 = split[1];
                    BigDecimal dwzh = new BigDecimal(s).divide(new BigDecimal(s1),7, BigDecimal.ROUND_HALF_UP);
                    //根据换算率换算 数量和单价 //商品数量
                    datamxx.put("spsl", new BigDecimal(taxxs1.getSli()).divide(dwzh, 6, BigDecimal.ROUND_HALF_UP).toString());
                    //含税单价
                    datamxx.put("hsdj", new BigDecimal(taxxs1.getHsdj()).multiply(dwzh).setScale(6, BigDecimal.ROUND_HALF_UP).toString());
                    //不含税单价
//                    datamxx.put("bhsdj", new BigDecimal(taxxs1.getWsdj()).multiply(dwzh).setScale(6, BigDecimal.ROUND_HALF_UP).toString());
                }
            } else{
                datamxx.put("spmc", taxxs1.getWlmc());
                //处理规格型号为~字符
                if(StringUtils.isNotEmpty(taxxs1.getGg()) && !"~".equals(taxxs1.getGg())){
                    datamxx.put("ggxh", taxxs1.getGg());
                }
                datamxx.put("jldw", taxxs1.getDwmc());
                //商品数量
                datamxx.put("spsl", taxxs1.getSli());
                //含税单价
                datamxx.put("hsdj", taxxs1.getHsdj());
                //不含税单价
//                datamxx.put("bhsdj", taxxs1.getWsdj());
            }

            datamxx.put("djhh", taxxs1.getHh());
            datamxx.put("spdm", taxxs1.getWlcode());
            datamxx.put("sppc", taxxs1.getPch());
            //含税金额
            datamxx.put("hsje", new BigDecimal(taxxs1.getBbjshj()).setScale(2,BigDecimal.ROUND_HALF_UP));
            //不含税金额
            datamxx.put("bhsje", new BigDecimal(taxxs1.getBbwsje()).setScale(2,BigDecimal.ROUND_HALF_UP));
            //税额
            datamxx.put("se", new BigDecimal(taxxs1.getShuie()).setScale(2,BigDecimal.ROUND_HALF_UP));
            //税率改为小数
            datamxx.put("tax", new BigDecimal(taxxs1.getSlv()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toString());
            datamxx.put("spbm", "");
            //零税率标识
            datamxx.put("lslbs", "");
            //优惠政策标识
            datamxx.put("yhzcbs", "");
            arraymxx.add(datamxx);
        }

        dataj1.put("hsbz", hsbz);
        dataj1.put("gsdm", taxxs.getGsdm());
        //内销:10；外销:20;内部交易:30
        dataj1.put("sjlx", "10");
        dataj1.put("sjly", "1");
        //开票类型 暂时0 kplx 0-正数开票(默认)；1-负数单据开票;3-作废单据
        dataj1.put("kplx", "0");
        dataj1.put("djbh", taxxs.getSoshid());
        dataj1.put("khdm", taxxs.getKpkh());
        dataj1.put("khmc", taxxs.getKhmc());
        //发票类型代码(32-01--004-专票 007- 普票 025-卷票 32-CXX-01--026-电子票 32-CXX-02--01-全电专 32-CXX-03--02-全电普)
        String fplx = taxxs.getFplx();
        if("32-01".equals(fplx)){
            dataj1.put("fplxdm", "004");
        }else if("32-Cxx-01".equals(fplx)){
            dataj1.put("fplxdm", "026");
        }else if("32-Cxx-02".equals(fplx)){
            dataj1.put("fplxdm", "01");
        }else if("32-Cxx-03".equals(fplx)){
            dataj1.put("fplxdm", "02");
        }
        //00-正常发票(默认) 08-成品油 02-收购发票 12-机动车专票
        dataj1.put("tspz", "00");
        dataj1.put("djrq", taxxs.getKprq());
        if(StringUtils.isNotEmpty(taxxs.getBz()) && !"~".equals(taxxs.getBz())){
            dataj1.put("bz", taxxs.getBz());
        }
        //含税标志
//        if (Integer.valueOf(taxxs.getSlv()) > 0) {
//            dataj1.put("hsbz", "1");
//        } else {
//            dataj1.put("hsbz", "0");
//        }
        //明细含税合计
//        dataj1.put("je", taxxs.getJshj());
        //税率改为小数
//        dataj1.put("tax", new BigDecimal(taxxs.getSlv()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toString());
        dataj1.put("djlx", "0");
        dataj1.put("kz1", taxxs.getDjh());
        dataj1.put("kz3", sfkjfp);
        dataj1.put("mxxx", arraymxx);
//        dataj1.put("tdhy",arraytdhy);

        JSONArray parray = new JSONArray();
        parray.add(dataj1);
        JSONObject pram = new JSONObject();
        pram.put("data", parray);

        String params = pram.toString();
        return params;
    }

    /**
     * 处理erp信息匹配到税务平台 外销
     */
    public String billPushTaxParamxsfpwx(List<Taxxs> mapslist, Boolean jsan) {
        Taxxs taxxs = mapslist.get(0);
        //判断内销和外销 内销和外销处理逻辑不一样
        String sfkjfp = taxxs.getSfkjfp();
        if (!"Y".equals(sfkjfp)){
            sfkjfp = "N";
        }
        //传金税按钮为真则直接放行 为假则进行是否传金税校验
        JSONObject dataj1 = new JSONObject();
        if(!jsan){
            //如果开具发票为Y则传金税 样品销售业务流则不传金税
            if(!"Y".equals(sfkjfp)|| "样品销售业务流".equals(taxxs.getYwlc()) ){
                return null;
            }
        }else{
            String pzh = taxxs.getPzh();
            String pzrq = taxxs.getPzrqn()+"-"+taxxs.getPzrqy();
            dataj1.put("kz2",pzh);
            dataj1.put("kz4",pzrq);
        }
        //处理参数
        JSONObject datatdhy = new JSONObject();
        datatdhy.put("tdyslxbl", "");
        datatdhy.put("tdyslx", "");
        datatdhy.put("tdysnr", "");
        JSONArray arraytdhy = new JSONArray();
        arraytdhy.add(datatdhy);
        BigDecimal bigDecimal = new BigDecimal("0");
        //动态添加 明细行信息
        JSONArray arraymxx = new JSONArray();
        //含税标识1含税,0不含税
        String hsbz = "0";
        for (Taxxs taxxs1 : mapslist) {
            //如果大于0则是1 不大于0不处理 明细中有一个含税则是1
            if (Integer.valueOf(taxxs1.getSlv()) > 0) {
                hsbz = "1";
            }
            if(StringUtils.isNotEmpty(taxxs1.getFobje())&& !"~".equals(taxxs1.getFobje())){
                bigDecimal = bigDecimal.add(new BigDecimal(taxxs1.getFobje()));
            }
            JSONObject datamxx = new JSONObject();
            datamxx.put("djhh", taxxs1.getHh());
            datamxx.put("spdm", taxxs1.getWlcode());
            //判断是否有报关商品名称 并判断是否是折扣行
            if(StringUtils.isNotEmpty(taxxs1.getBgspmc()) && !taxxs1.getBgspmc().equals("~")){
                datamxx.put("spmc", taxxs1.getBgspmc());
            }else{
                datamxx.put("spmc", taxxs1.getWlmc());
            }
            if("折扣".equals(datamxx.get("spmc"))){
                if(StringUtils.isNotEmpty(taxxs.getBgspmc()) && !taxxs.getBgspmc().equals("~")){
                    datamxx.put("spmc", taxxs.getBgspmc());
                }else{
                    datamxx.put("spmc", taxxs.getWlmc());
                }
            }else{
                //处理规格型号为~
                if(StringUtils.isNotEmpty(taxxs1.getGg()) && !"~".equals(taxxs1.getGg())){
                    datamxx.put("ggxh", taxxs1.getGg());
                }
                //数量和单位转换
                datamxx.put("spsl", taxxs1.getSli());
                datamxx.put("jldw", taxxs1.getDwmc());
                if("吨".equals(taxxs1.getDwmc())){
                    //如果是吨则需要变换单位 和数量
                    datamxx.put("jldw", "千克");
                    datamxx.put("spsl",new BigDecimal(taxxs1.getSli()).multiply(new BigDecimal("1000")).toString());
                }else if("公斤".equals(taxxs1.getDwmc())){
                    datamxx.put("jldw", "千克");
                }

                datamxx.put("sppc", taxxs1.getPch());
            }

            //只传 fob无税金额和含税金额
            //含税单价
//            datamxx.put("hsdj", taxxs1.getHsdj());
            //不含税单价
//            datamxx.put("bhsdj", taxxs1.getWsdj());
            //含税金额
            if(StringUtils.isNotEmpty(taxxs1.getFobbbjshj())  && !"~".equals(taxxs1.getFobbbjshj())){
                datamxx.put("hsje", new BigDecimal(taxxs1.getFobbbjshj()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            }
            //不含税金额
            if(StringUtils.isNotEmpty(taxxs1.getFobbbwsje())  && !"~".equals(taxxs1.getFobbbwsje())){
                datamxx.put("bhsje", new BigDecimal(taxxs1.getFobbbwsje()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            }
            //税额
            if(StringUtils.isNotEmpty(taxxs1.getFobbbse())  && !"~".equals(taxxs1.getFobbbse())){
                datamxx.put("se", new BigDecimal(taxxs1.getFobbbse()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
            }
            //税率改为小数
            if(StringUtils.isNotEmpty(taxxs1.getSlv())  && !"~".equals(taxxs1.getSlv())){
                datamxx.put("tax", new BigDecimal(taxxs1.getSlv()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toString());
            }
            datamxx.put("spbm", "");
            //零税率标识
            datamxx.put("lslbs", "");
            //优惠政策标识
            datamxx.put("yhzcbs", "");
            arraymxx.add(datamxx);
        }

        //含税标志
//        if (Integer.valueOf(taxxs.getSlv()) > 0) {
//            dataj1.put("hsbz", "1");
//        } else {
//            dataj1.put("hsbz", "0");
//        }
        dataj1.put("hsbz", hsbz);
        dataj1.put("gsdm", taxxs.getGsdm());
        //内销:10；外销:20;内部交易:30
        dataj1.put("sjlx", "20");
        dataj1.put("sjly", "1");
        //开票类型 暂时0 fplx
        dataj1.put("kplx", "0");
        dataj1.put("djbh", taxxs.getSoshid());
        dataj1.put("khdm", taxxs.getKpkh());
        dataj1.put("khmc", taxxs.getKhmc());
        //发票类型代码(32-01--004-专票 007- 普票 025-卷票 32-CXX-01--026-电子票 32-CXX-02--01-全电专 32-CXX-03--02-全电普)
        String fplx = taxxs.getFplx();
        if("32-01".equals(fplx)){
            dataj1.put("fplxdm", "004");
        }else if("32-Cxx-01".equals(fplx)){
            dataj1.put("fplxdm", "026");
        }else if("32-Cxx-02".equals(fplx)){
            dataj1.put("fplxdm", "01");
        }else if("32-Cxx-03".equals(fplx)){
            dataj1.put("fplxdm", "02");
        }
        //00-正常发票(默认) 08-成品油 02-收购发票 12-机动车专票
        dataj1.put("tspz", "00");
        dataj1.put("djrq", taxxs.getKprq());
        //备注 将贸易方式、结算方式、装运港（显示为发地港）、运输方式、FOB金额（原币合计金额）、币种、汇率、报关单号以“；”隔开，组合成一个字段；
        String fobje = bigDecimal.toString();
        String bz = "";

        if(StringUtils.isNotEmpty(taxxs.getMyfs()) && !"~".equals(taxxs.getMyfs())) bz = bz + "贸易方式: "+taxxs.getMyfs()+";";
//        if(StringUtils.isNotEmpty(taxxs.getJsfs()) && !"~".equals(taxxs.getJsfs())) bz = bz + "结算方式: "+taxxs.getJsfs()+";";
        bz = bz + "结算方式: "+"电汇;";
        if(StringUtils.isNotEmpty(taxxs.getZyg()) && !"~".equals(taxxs.getZyg())) bz = bz + "装运港: "+taxxs.getZyg()+";";
        if(StringUtils.isNotEmpty(taxxs.getYsfs()) && !"~".equals(taxxs.getYsfs())) bz = bz + "运输方式: "+taxxs.getYsfs()+";";
        if(StringUtils.isNotEmpty(fobje) && !"~".equals(fobje)) bz = bz + "FOB金额: "+fobje+";";
        if(StringUtils.isNotEmpty(taxxs.getBiz()) && !"~".equals(taxxs.getBiz())) bz = bz + "币种: "+taxxs.getBiz()+";";
        if(StringUtils.isNotEmpty(taxxs.getHuilv()) && !"~".equals(taxxs.getHuilv())) bz = bz + "汇率: "+taxxs.getHuilv()+";";
        if(StringUtils.isNotEmpty(taxxs.getBgdh()) && !"~".equals(taxxs.getBgdh())){
            bz = bz + "报关单号: "+taxxs.getBgdh()+";";
            dataj1.put("kz6", taxxs.getBgdh());
        }
//        bz = taxxs.getMyfs()+";"+taxxs.getJsfs()+";"+taxxs.getZyg()+";"+taxxs.getYsfs()+";"+fobje+";"+taxxs.getBiz()+";"+taxxs.getHuilv()+";"+taxxs.getBgdh();
//        String[] split = bz.split(";");
//        List<String> list = new ArrayList<>();
//        for (String s : split) {
//            if(!"null".equals(s) && !"~".equals(s)){
//                list.add(s);
//            }
//        }
//        String bz1 = "";
//        for (String s : list) {
//            bz1 = bz1+s;
//        }
        dataj1.put("bz", bz);
        //明细行含税合计
//        dataj1.put("je", taxxs.getJshj());
        //税率改为小数
//        dataj1.put("tax", new BigDecimal(taxxs.getSlv()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP).toString());
        dataj1.put("djlx", "0");
        dataj1.put("kz1", taxxs.getDjh());
        dataj1.put("kz3", sfkjfp);
        dataj1.put("mxxx", arraymxx);
//        dataj1.put("tdhy",arraytdhy);

        JSONArray parray = new JSONArray();
        parray.add(dataj1);
        JSONObject pram = new JSONObject();
        pram.put("data", parray);

        String params = pram.toString();
        return params;
    }

    //清空防止多次回调id
    public void deletenotifyall(){
        apiLogMapper.deletenotifyall();
    }

    /**
     * @author: LiuJiaji
     * @date: 2025/5/16 16:28
     * @description: TODO 客户信息推送到金税平台 定时任务推送一天推送两次
     * @param:
     * @return:
     **/
    public void pushCustomer(String times, String timee){
        TaxCustomerInfo taxCusinfp = new TaxCustomerInfo();
        taxCusinfp.setDateTimes(times);
        taxCusinfp.setDateTimee(timee);
        List<TaxCustomerInfo> all = taxCustomerInfoMapper.findAll(taxCusinfp);
        JSONObject paramj = new JSONObject();
        paramj.put("serverId","K0004");
        JSONArray jsona = new JSONArray();
        for (TaxCustomerInfo taxCustomerInfo : all) {
            JSONObject paramz = new JSONObject();
            paramz.put("khmc",taxCustomerInfo.getCuname());
            if(StringUtils.isNotBlank(taxCustomerInfo.getCutaxid()) && !"~".equals(taxCustomerInfo.getCutaxid())){
                paramz.put("khsh",taxCustomerInfo.getCutaxid());
            }else{
                paramz.put("khsh","");
            }
            paramz.put("khdm",taxCustomerInfo.getCucode());
            paramz.put("yhmc",taxCustomerInfo.getKhhname());
            paramz.put("yhkh",taxCustomerInfo.getCbankcode());
            paramz.put("khdz",taxCustomerInfo.getCuaddress());
            paramz.put("gsdm",taxCustomerInfo.getSalesorg());
            String email = taxCustomerInfo.getEmail();
            if(StringUtils.isNotEmpty(email)){
                paramz.put("email",email);
            }
            jsona.add(paramz);
        }
        paramj.put("content",jsona);
        String desc = "erp客户信息同步金税";
        String params = paramj.toString();
        String url = sendUrl + "/basic/syncData.do";
        logger.info(desc+"接口 地址: " + url);
        logger.info(desc+"接口 入参: " + params);
        String s = OkHttpUtils.okHttpPost(url, params);
        logger.info(desc+"接口 返参: " + s);
    }

}
